<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../vue.js"></script>
</head>

<body>
    <div id="app">
        <input type="text" v-model="str">
        <button @click="sort(0)">正常排序</button>
        <button @click="sort(1)">升序</button>
        <button @click="sort(2)">将序</button>

        <ul>
            <li v-for="item in person2" :key="item.id">
                {{item.name}} -- {{item.age}} -- {{item.gender}}
            </li>
        </ul>
    </div>
    <script>
        Vue.config.productionTip = false;

        const vm = new Vue({
            el: "#app",
            data() {
                return {
                    str: '',
                    person: [
                        { id: '001', name: '马冬梅', age: 25, gender: '女' },
                        { id: '002', name: '周冬雨', age: 20, gender: '女' },
                        { id: '003', name: '周杰伦', age: 21, gender: '男' },
                        { id: '004', name: '帅邓伦', age: 22, gender: '男' },
                    ],
                    person2: [],
                    type: 0
                }
            },
            //监听配置
            watch: {
                str: {
                    //初始立即监听
                    immediate: true,
                    handler(value) {
                        //过滤
                        const newarr = this.person.filter(item => {
                            return item.name.indexOf(value) !== -1
                        })

                        if (this.type === 0) {
                            this.person2 = newarr
                        }

                        //排序
                        newarr.sort((a, b) => {
                            return this.type === 1 ? a.age - b.age : b.age - a.age
                        })

                        //赋值给data中的person2
                        this.person2 = newarr
                    }
                }
            },
            methods: {
                sort(index) {
                    this.type = index
                }
            }
        })

    </script>
</body>

</html>